﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Com.Pernix.Component.Member;
using Com.Pernix.Component.Member.Models;
using OnlineExamination.Areas.Members.Models;
using Com.Pernix.Component.Member.BL.Repositories;

namespace OnlineExamination.Areas.Members.Controllers
{
    public class LoginController : Controller
    {
        private static readonly UnitOfWork UnitOfWork = new UnitOfWork(NHibernateHelper.SessionFactory);
        //
        // GET: /Members/Login/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(UserLoginDto userLoginDto)
        {
            using (var userRepos = new UserRepository(UnitOfWork))
            {
                var validUser = userRepos.VerifyUser(new User
                                         {
                                             Username = userLoginDto.Username,
                                             Password = userLoginDto.Password
                                         });
                if(validUser)
                {
                    Session["IsLogin"] = true;
                    var usernameCookie = new HttpCookie("username", userLoginDto.Username);
                    usernameCookie.Domain = "localhost";
                    var passwordCookie = new HttpCookie("password", userLoginDto.Password);
                    passwordCookie.Domain = "localhost";
                    Response.Cookies.Add(usernameCookie);
                    Response.Cookies.Add(passwordCookie);
                    return RedirectToAction("Main", "Home", new { area = "" });
                    //return RedirectToAction("Main", "Home");
                }
            }
            return RedirectToAction("Fail");
        }
        public ActionResult Success(UserLoginDto userLoginDto)
        {
            return View(userLoginDto);
        }

        public String Fail()
        {
            return "Login Fail.";
        }
    }
}
